//
//  PeripheralViewController.swift
//  SwiftLearnAll
//
//  Created by iosdev1 on 2017/8/6.
//  Copyright © 2017年 ygsoft. All rights reserved.
//

import UIKit
import CoreBluetooth

class PeripheralViewController: ZyBaseViewController, CBPeripheralManagerDelegate {

    let SERVICE_UUID = "0000ffe0-0000-1000-8000-00805f9b34fb"
    let CHARACTERISTIC_UUID = "0000ffe1-0000-1000-8000-00805f9b34fb"
//    let SERVICE_UUID = "CDD1"
//    let CHARACTERISTIC_UUID = "CDD2"

    var cbPeripheralManager:CBPeripheralManager?
    var cbCharacteristic:CBMutableCharacteristic?

    var tfdStr:String = "空数据"

    @IBOutlet weak var btnSend: UIButton!
    @IBOutlet weak var tfdSend: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "蓝牙外设"
        self.setMyPeripheralManager()
    }
    @IBAction func tfdEditingEnd(_ sender: UITextField) {
        tfdStr = sender.text!;
    }


    @IBAction func btnClick(_ sender: UIButton) {
        tfdSend.endEditing(true)
        let sendSuccess:Bool! = cbPeripheralManager!.updateValue(tfdStr.data(using: String.Encoding.utf8)!, for: cbCharacteristic!, onSubscribedCentrals: nil);
        if sendSuccess == true {
            print("发送成功")
        }else{
            print("发送失败")
        }

    }

    func setMyPeripheralManager() -> Void {
        cbPeripheralManager = CBPeripheralManager.init(delegate: self, queue: DispatchQueue.main);
    }

    /** 设备的蓝牙状态
     CBManagerStateUnknown = 0,  未知
     CBManagerStateResetting,    重置中
     CBManagerStateUnsupported,  不支持
     CBManagerStateUnauthorized, 未验证
     CBManagerStatePoweredOff,   未启动
     CBManagerStatePoweredOn,    可用
     */

    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        if #available(iOS 10.0, *) {
            // 创建Service（服务）和Characteristics（特征）
            if peripheral.state == CBManagerState.poweredOn {
                self.setupServiceAndCharacteristics()
                cbPeripheralManager?.startAdvertising([CBAdvertisementDataServiceUUIDsKey:[CBUUID.init(string: SERVICE_UUID)]]);
            }
        } else {
            // Fallback on earlier versions
        }
    }
/** 创建服务和特征 */
    func setupServiceAndCharacteristics() -> Void {
        // 创建服务
        let serviceID:CBUUID = CBUUID.init(string: SERVICE_UUID)
        let service:CBMutableService = CBMutableService.init(type: serviceID, primary: true);

        // 创建服务中的特征;
        let properties = CBCharacteristicProperties.read.rawValue | CBCharacteristicProperties.notify.rawValue | CBCharacteristicProperties.write.rawValue
        let permissions = CBAttributePermissions.readable.rawValue|CBAttributePermissions.writeable.rawValue

        let characteristicID:CBUUID = CBUUID.init(string: CHARACTERISTIC_UUID);
        let characteristic:CBMutableCharacteristic = CBMutableCharacteristic.init(type: characteristicID, properties: CBCharacteristicProperties(rawValue: properties), value: nil, permissions: CBAttributePermissions(rawValue: permissions));

        // 特征添加进服务
        service.characteristics = [characteristic]

        // 服务加入管理
        cbPeripheralManager?.add(service);

        // 为了手动给中心设备发送数据
        cbCharacteristic = characteristic;
    }

    /** 中心设备读取数据的时候回调 */
    func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
        // 请求中的数据，这里把文本框中的数据发给中心设备
        request.value = tfdSend.text?.data(using: String.Encoding.utf8)
        peripheral.respond(to: request, withResult: CBATTError.success);
    }

    /** 中心设备写入数据的时候回调 */
    func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
        // 写入数据的请求
        let request:CBATTRequest = requests.last!;
        tfdSend.text = String.init(data: request.value!, encoding: String.Encoding.utf8);
    }

    /** 订阅成功回调 */
    func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
        print("订阅成功回调")
    }

    /** 取消订阅回调 */
    func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {
        print("/** 取消订阅回调 */")
    }



    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
